export module MapTex;

import DND;

import DefVar;
import DefOrder;


//纹理地图，用于地图缩小时显示，从而不绘制精灵
export class MapTex
{
public:
	void Init(Coor* coor)
	{
		_bNeedRefresh = false;
		//img
		_img = Image::Create(DefVar::SIZE_MAP_TEX, g_factory->GetColor("terrain_ocean"));

		//tex
		g_system->Lock();
		_tex = Texture::Create();
		_tex->Init(Constant::ID_START_TEXTURE_USER, DefVar::SIZE_MAP_TEX, _img);
		g_system->UnLock();

		//spr
		g_factory->CreateCanvas(_tex);
		_spr = g_factory->CreateSprite(Constant::ID_START_TEXTURE_USER,
			createRectU({ 0, 0 }, DefVar::SIZE_MAP_TEX));
		//大小为 纹理大小 * 格子大小
		Quad quad = createQuad(DefVar::SIZE_MAP_TEX * (natural)DefVar::NODE_PIXEL, false);
		//偏移为原点位置 * 格子大小
		Vector2 offset = toVector2(-DefVar::OFFSET_MAP_TEX) * DefVar::NODE_PIXEL;
		_spr->SetQuad(quad + offset);
		_spr->SetCoor(coor);
		_spr->SetOrder(DefOrder::TERRAIN);
		_spr->SetSampler(Sprite::Sampler::PIXEL);
	}

	void Set(const PointU& xy, const Color& col)
	{
		_img->SetDotColor(xy, col);
		_bNeedRefresh = true;
	}

	void Render()
	{
		if (_bNeedRefresh)
		{
			_bNeedRefresh = false;
			_refresh();
		}
		_spr->Render();
	}
	~MapTex()
	{
		delete _img;
	}
private:
	Texture* _tex;
	gcSprite _spr;
	Image* _img;
	bool _bNeedRefresh;

	void _refresh()
	{
		g_system->Lock();
		_tex->Update({}, _img, createRectU({ 0, 0 }, DefVar::SIZE_MAP_TEX));
		g_system->UnLock();
	}
};


//! ll到纹理
export Point LL2MapTex(const Point& xy)
{
	return xy + DefVar::OFFSET_MAP_TEX;
}